package com.sdry.system.controller;



import com.sdry.system.entity.RoleUser;
import com.sdry.system.entity.SysUser;
import com.sdry.system.service.RoleService;
import com.sdry.system.service.UserService;
import com.sdry.untils.JwtUtil;
import com.sdry.untils.Md5Util;
import com.sdry.untils.VerifyCodeUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;


/**
 * 登录管理
 * @author chenbin
 * @date 2020年1月13日16:36:07
 */
@Controller
public class LoginController {

    @Autowired
    private UserService userService;

    @Autowired
    private RoleService roleService;

    @RequestMapping("/login")
    public String login() {
       return "login";
    }


    /**
     * 登录
     * @param user 用户信息
     * @param model 返回
     * @param request 请求
     * @param code 验证码
     * @return
     */
    @RequestMapping("/toLogin")
    public String login(SysUser user, Model model, HttpServletRequest request, String code) {
        user.setPassword(Md5Util.encrypt(user.getPassword()));
        UsernamePasswordToken token = new UsernamePasswordToken(user.getUsername(),user.getPassword());
        Subject subject = SecurityUtils.getSubject();
        try {
            //登陆成功
            subject.login(token);
            SysUser user1 = (SysUser) subject.getPrincipal();
            //当前用户所有的角色
            List<RoleUser> roleUsers =  userService.queryRoleUserByUserIdList(user1.getUserId());
            user1.setRoleUserList(roleUsers);
            //当前角色对应的菜单
            List<Long> menuIdList = new ArrayList<>();
            for (RoleUser roleUser : roleUsers) {
                List<Long> list = roleService.queryRoleMenuList(roleUser.getRoleId());
                menuIdList.addAll(list);
            }
            HashSet set = new HashSet(menuIdList);
            menuIdList.clear();
            menuIdList.addAll(set);
            user1.setMenuIdList(menuIdList);
            //token
            String tokenString = JwtUtil.sign(user1.getUsername(), user1.getPassword());
            if (tokenString != null) {
                request.getSession().setAttribute("Token",tokenString);
            }
            //session
            request.getSession().setAttribute("user",user1);
        } catch (UnknownAccountException uae) {
            model.addAttribute("message","账号不正确!");
            return "login";

        } catch (IncorrectCredentialsException ice) {
            model.addAttribute("message","密码不正确!");
            return "login";

        } catch (LockedAccountException lae) {
            model.addAttribute("message","账号被锁定!");
            return "login";

        } catch (AuthenticationException ae) {
            //model.addAttribute("message","登录出错!");
            return "login";
        }
        return "index";
    }

    /**
     * 登录管理
     * @return
     */
    @RequestMapping(value = "/loginOut")
    public String loginOut(HttpServletRequest request) {
        SecurityUtils.getSubject().logout();
        request.getSession().invalidate();
        return "login";
    }


    /**
     * 主页面显示
     * @return
     */
    @RequestMapping(value = "showMain")
    public String showMain() {
        return "main";
    }


    @GetMapping(value = "/getCode")
    public void getYzm(HttpServletResponse response, HttpServletRequest request) {
        try {
            response.setHeader("Pragma", "No-cache");
            response.setHeader("Cache-Control", "no-cache");
            response.setDateHeader("Expires", 0);
            response.setContentType("image/jpg");

            //生成随机字串
            String verifyCode = VerifyCodeUtils.generateVerifyCode(4);
            //log.info("verifyCode:{}", verifyCode);
            //存入会话session
            HttpSession session = request.getSession(true);
            session.setAttribute("_code", verifyCode.toLowerCase());
            //生成图片
            int w = 146, h = 33;
            VerifyCodeUtils.outputImage(w, h, response.getOutputStream(), verifyCode);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
